import Taro from '@tarojs/taro'
import * as _ from 'lodash'
import { baseURL } from './baseUrl'

import { store } from '../store'

export const baseUrl: string = baseURL
export interface ResData {
  status?: 'ok' | 'error'
  code?: 0 | 1
  msg?: string
  [key: string]: any
}
// ? 数据转换
export function initResData(res) {
  const { data: dataInRes, colunms, ...theRest } = res
  if (Array.isArray(dataInRes) && Array.isArray(colunms)) {
    let keyIdx = -1
    let idIdx = -1
    colunms.forEach((e, idx) => {
      if (e === 'id') {
        idIdx = idx
      } else if (e === 'key') {
        keyIdx = idx
      }
    })

    // 压缩传输，要进行转换
    res.data = dataInRes.map((row, index) => {
      const rowObj = {
        key: `${index}${`${new Date().getTime()}${index + Math.random()}`}`,
      }
      if (keyIdx === -1 && idIdx !== -1) {
        rowObj.key = row[idIdx]
      }
      row.forEach((col, colIdx) => {
        rowObj[colunms[colIdx]] = col
      })
      return rowObj
    })
    delete res.colunms
  }
  return { ...res, ...theRest }
}
// ? 从缓存中拿 集团id和店铺id
const getStoreData = () => {
  const { user = {} } = store.getState()
  return {
    nickName: user.nickName,
    openId: user.openId,
    unionId: user.unionId,
    adm_id: user.id,
    inst_code: user.lmnid,
    inst_name: user.name,
  }
}

const defaultHeader = {
  'content-type': 'application/json',
}
function color16() {
  // ! 调试模式下专用
  var r = Math.floor(Math.random() * 256)
  var g = Math.floor(Math.random() * 256)
  var b = Math.floor(Math.random() * 256)
  var color = '#' + r.toString(16) + g.toString(16) + b.toString(16)
  return color
}
export const request = (params): Promise<ResData> => {
  const { url, data, method = 'POST', header = {} } = params

  return new Promise((resolve, reject) => {
    const sendData = {
      ...getStoreData(),
      ...data,
    }
    const thatcolor = color16() // ! 调试模式下专用
    console.log(
      '%c ' + `http发送:${baseUrl}${url}:`,
      `color: ${thatcolor};font-size:28px`
    )
    console.log(sendData)
    Taro.request({
      url: baseUrl + url,
      data: sendData,
      method,
      header: {
        ...defaultHeader,
        ...header,
      },
      success: (res) => {
        const newData = initResData(res.data) // ! 调试模式下专用
        console.log(
          '%c ' + `http接收:${baseUrl}${url}:`,
          `color: ${thatcolor};font-size:28px`
        )
        console.log(newData)
        resolve(newData)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
